package {{.table}}

import (
	"fmt"
	"sync"
	"xian-server/lib/database"
	"xian-server/lib/utils/transf"
)

type {{.schema.Opts.UpperCamelCaseTable}}Dao struct {
	Model *{{.schema.Opts.UpperCamelCaseTable}}
}

var (
	instance{{.schema.Opts.UpperCamelCaseTable}}Dao *{{.schema.Opts.UpperCamelCaseTable}}Dao //单例的对象
	once{{.schema.Opts.UpperCamelCaseTable}}Dao     sync.Once
)

func New{{.schema.Opts.UpperCamelCaseTable}}Dao() *{{.schema.Opts.UpperCamelCaseTable}}Dao {
	once{{.schema.Opts.UpperCamelCaseTable}}Dao.Do(func() {
		instance{{.schema.Opts.UpperCamelCaseTable}}Dao = &{{.schema.Opts.UpperCamelCaseTable}}Dao{Model: New{{.schema.Opts.UpperCamelCaseTable}}Model()}
	})
	return instance{{.schema.Opts.UpperCamelCaseTable}}Dao
}

// 创建
func (d *{{.schema.Opts.UpperCamelCaseTable}}Dao) Create{{.schema.Opts.UpperCamelCaseTable}}(model *{{.schema.Opts.UpperCamelCaseTable}}) (string, error) {
	fields, vals := transf.GetStructKV(model, []string{"id"}, true)
	id, err := database.NewDAO(d.Model).Insert(fields, vals)
	if err != nil {
		return "", err
	}

	fmt.Printf("result: %v\n", id)
	return id, nil
}

// 根据 id 删除 {{.schema.Opts.TableComment}}
func (d *{{.schema.Opts.UpperCamelCaseTable}}Dao) Delete{{.schema.Opts.UpperCamelCaseTable}}ById(id *{{.schema.Opts.UpperCamelCaseTable}}Id) error {
	_, err := database.NewDAO(d.Model).Delete(string(*id))
	if err != nil {
		return err
	}
	return nil
}

// 根据 id 修改 {{.schema.Opts.TableComment}}
func (d *{{.schema.Opts.UpperCamelCaseTable}}Dao) Update{{.schema.Opts.UpperCamelCaseTable}}ById(id *{{.schema.Opts.UpperCamelCaseTable}}Id, model *{{.schema.Opts.UpperCamelCaseTable}}) error {
	fields, vals := transf.GetStructKV(model, []string{"id"}, true)
	_, err := database.NewDAO(d.Model).Update(fields, vals, "")
	if err != nil {
		return err
	}
	return nil
}

// 查询全部 {{.schema.Opts.TableComment}}
func (d *{{.schema.Opts.UpperCamelCaseTable}}Dao) FindAll{{.schema.Opts.UpperCamelCaseTable}}() (*[]{{.schema.Opts.UpperCamelCaseTable}}, error) {
	list := d.Model.NewSplice()
	if err := database.NewDAO(d.Model).Lists(list, ""); err != nil {
		return list, err
	}
	return list, nil
}
